import api from '@/api'

export default {
  namespaced: true,
  state: {
    car_products: []
  },
  getters: {
    count (state) {
      return state.car_products.reduce((prevValue, item, index) => {
        if (item.is_active === '1') {
          return prevValue + item.num
        }
        return prevValue
      }, 0)
    },
    isCheckAll (state) {
      return state.car_products.reduce((prevValue, item, index) => {
        if (!prevValue) {
          return false
        }
        return item.is_active === '1'
      }, true)
    },
    ids (state) {
      return state.car_products.map(item => item.id)
    },
  },
  mutations: {
    SET_CARPRODUCTS (state, payload) {
      state.car_products = payload
    }
  },
  actions: {
    async getCarProducts ({ commit, dispatch }) {
      const res = await api.car.list()
      commit('SET_CARPRODUCTS', res.data)
    },
    async add ({ dispatch }, payload) {
      await api.car.add(payload.id)
      dispatch('getCarProducts')
    },
    async update({ dispatch }, payload) {
      await api.car.update(payload)
      dispatch('getCarProducts')
    }
  }
}
